<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <script>
    const l1 = [1, 2, 3, 4, 5];
    function ListNode(val) {
      this.val = val;
      this.next = null;
    }
    /**
     * https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/
     * 思路：我们通过反转链表来删除第n个节点，即是删除了倒数第n个节点
     *        查找节点，通过遍历位置得到
     * 此处不需反转
     * 举个栗子
     * 1 -> 2 -> 3 -> 4 -> 5
     * 删除倒数第2个节点，等价于
     * 删除正数第4(5 - 2 + 1)个节点
     * 因此此题转换成了删除正数第(L - n + 1)个节点
     * L为链表长度，需要通过遍历算得
     * 然后解法同正数的相同即可
     */ 
    function removeNthfromEnd(head, n) {
      let preHead = new ListNode(-1);
      preHead.next = head;
      let len = 0;
      let first = head;

      while (first !== null) {
        len++;
        first = first.next;
      }
      len -= n;
      first = preHead;
      while (len !== 0) {
        len--;
        first = first.next;
      }
      first.next = first.next.next;
      return preHead.next;
    }
    console.log(removeNthfromEnd(l1, 2));
  </script>
</body>
</html>